package com.dsteiner.xelavos.client.controller;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

import com.dsteiner.widgets.client.IJsUtil;
import com.dsteiner.xelavos.client.constants.Constants;
import com.dsteiner.xelavos.client.model.AuthenticationModel;
import com.google.gwt.event.logical.shared.ResizeEvent;
import com.google.gwt.event.logical.shared.ResizeHandler;
import com.google.gwt.user.client.ui.RootPanel;

public class WindowController implements Constants{

	private RootPanel contentTabRootPanel;
	private IJsUtil jsUtil;
	private RootPanel contentRootPanel;
	private RootPanel contentMainRootPanel;
	private AuthenticationModel authenticationModel;

	public void registerJsUtil(IJsUtil jsUtil) {
		this.jsUtil = jsUtil;
		jsUtil.addWindowResizeHandler(new ResizeHandler(){
			public void onResize(ResizeEvent event) {
				updateWidgetSizes();
			}
		});
		updateWidgetSizes();
	}

	private void updateWidgetSizes() {
		if(contentTabRootPanel != null){
			int width = jsUtil.getClientWidth();
			contentTabRootPanel.setWidth((width - WIDTH_USERS_PANEL) + "px");
		}
		if(contentMainRootPanel != null){
			int width = jsUtil.getClientWidth();
			contentMainRootPanel.setWidth((width - WIDTH_USERS_PANEL) + "px");
		}
		if(contentRootPanel != null){
			int height = jsUtil.getClientHeight();
			contentRootPanel.setHeight((height - Constants.Util.getHeaderHeight(authenticationModel.getUser())) + "px");
		}
	}

	public void registerContentTabRootPanel(RootPanel contentTabRootPanel) {
		this.contentTabRootPanel = contentTabRootPanel;
	}
	
	public void registerAuthenticationModel(AuthenticationModel authenticationModel) {
		this.authenticationModel = authenticationModel;
		authenticationModel.addPropertyChangeListener("user", new PropertyChangeListener(){
			public void propertyChange(PropertyChangeEvent evt) {
				updateWidgetSizes();
			}
		});
	}

	public void registerContentRootPanel(RootPanel contentRootPanel) {
		this.contentRootPanel = contentRootPanel;
	}

	public void registerContentMainRootPanel(RootPanel contentMainRootPanel) {
		this.contentMainRootPanel = contentMainRootPanel;
	}

}
